package com.example.notificationdemo;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnSend = findViewById(R.id.btn_send);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                Notification.Builder builder;
                int channelId = 100;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {        //Android 8.0以上
                    NotificationChannel channel = new NotificationChannel(String.valueOf(channelId),
                            "channel_name",
                            NotificationManager.IMPORTANCE_HIGH);
                    manager.createNotificationChannel(channel);
                    builder = new Notification.Builder(MainActivity.this, String.valueOf(channelId));
                } else {
                    builder = new Notification.Builder(MainActivity.this);
                }
                Intent intent = new Intent(Intent.ACTION_CALL_BUTTON);
                PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
                builder.setContentTitle("来电通知")            //指定通知栏的标题内容
                        .setContentText("刚才你的好朋友张三给你来电话。")             //通知的正文内容
                        .setWhen(System.currentTimeMillis())                //通知创建的时间
                        .setSmallIcon(R.mipmap.ic_launcher)    //通知显示的小图标，只能用alpha图层的图片进行设置
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .setVibrate(new long[]{0, 50, 100, 150})
                        .setContentIntent(pi);

                Notification notification = builder.build();
                //channelId为本条通知的id
                manager.notify(channelId, notification);
            }
        });
    }
}